package com.xiaobai.controller;

import com.alibaba.fastjson.JSON;
import com.xiaobai.common.ServiceResponse;
import com.xiaobai.dao.QualityDao;
import com.xiaobai.service.quality.IQualityService;
import com.xiaobai.units.HttpUnits_V2;
import com.xiaobai.vo.AllQuality;
import com.xiaobai.vo.QualityItem;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/quality")
@Slf4j
public class QualityController {

    @Autowired
    private QualityDao qualityDao;

    @Autowired
    private IQualityService qualityService;

    final String url="https://jwxt.gdupt.edu.cn/xsktsbxx!getYxktDataList.action";

    /**
     * 更新素拓分
     * @param student_id
     * @param jsessionid
     * @return
     */
    @GetMapping("/selectNewQuality")
    public ServiceResponse<List<QualityItem>> selectNewQuality(String student_id,String jsessionid){

        Calendar calendar = Calendar.getInstance();
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        if (hour >= 23 || hour <= 6) {
            return ServiceResponse.fail("教务网休息了");
        }

        Map<String,Object> map=new HashMap<>();

        map.put("page","1");
        map.put("rows","55");
        map.put("sort","cjsj");
        map.put("order","desc");

        String result = HttpUnits_V2.commonGyPost(url, map, jsessionid);

        if(result.length()<30){
            //教务bug返回素拓为空了,就不更新数据库了
            log.error("更新素拓时,返回数据为空,备用数据库");
            AllQuality allQuality = qualityService.allQualityJSONByDB(student_id);
            return ServiceResponse.createBySuccess(allQuality.getQualityItemList());
        }

        int startIndex=result.indexOf("\"rows\":")+7;
        int endIndex=result.length()-1;

        result=result.substring(startIndex,endIndex);

        List<String> listJSON= JSON.parseArray(result,String.class);

        AllQuality allQuality=new AllQuality();

        for(int i=0;i<listJSON.size();i++){
            QualityItem qualityItem=JSON.parseObject(listJSON.get(i),QualityItem.class);
            qualityItem.setKtmc(qualityItem.getKtmc().replaceAll("&ldquo;","\""));
            qualityItem.setKtmc(qualityItem.getKtmc().replaceAll("&rdquo;","\""));
            qualityItem.setKtmc(qualityItem.getKtmc().replaceAll("&middot;","-"));
            allQuality.getQualityItemList().add(qualityItem);
        }

        /**该存入数据库了
         */
        qualityDao.updateOrInsertQuality(student_id,JSON.toJSONString(allQuality.getQualityItemList()));

        return ServiceResponse.createBySuccess(allQuality.getQualityItemList());
    }

}
